#!/usr/bin/python

import threading, time, random

def gen(sem, queue, qlock):
		while(1):
				time.sleep(0.1)
				if random.randint(0,1):
						value=random.randint(0,10)
						qlock.acquire()
						try:
								queue.append(value)
						finally:
								qlock.release()
						print "generate %d"%value
						sem.release()
							

def use(sem,queue,qlock):
	while 1:
		sem.acquire()
		qlock.acquire()
		try:
				value=queue.pop(0)
				print "%s got %d" %(threading.currentThread().getName(),value)
		finally:
				qlock.release()
		time.sleep(random.randint(0,3))

childthread =[]
sem=threading.Semaphore(0)
queue=[]
qlock=threading.Lock()


#the producting thread		
tgen=threading.Thread(target=gen,args=[sem,queue,qlock])
tgen.setDaemon(1)
tgen.start()

#the consumer thread
for i in range(1,5):
		t=threading.Thread(target=use,args=[sem,queue,qlock])
		t.setDaemon(1)
		t.start()
		childthread.append(t)
while(1):
		time.sleep(30)
